//
//  WYMomentPhotosView.m
//  FriendCircleDemo
//
//  Created by WY on 2018/9/28.
//  Copyright © 2018年 WY. All rights reserved.
//

#import "WYMomentPhotosView.h"
#import "WYMomentPhotoView.h"
#import "YYPhotoGroupView.h"
@implementation WYMomentPhotosView

-(instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        
        for (NSInteger i = 0; i < WYMomentPhotosMaxCount; i++) {
            WYMomentPhotoView *photoView = [[WYMomentPhotoView alloc] init];
            photoView.backgroundColor = self.backgroundColor;
            photoView.hidden = YES;
            photoView.tag = i;
            [self addSubview:photoView];
            
            UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] init];
            [recognizer addTarget:self action:@selector(tapPhoto:)];
            [photoView addGestureRecognizer:recognizer];
        }
    }
    return self;
}

-(void)setPicInfos:(NSArray<WYPicture *> *)picInfos
{
    _picInfos = picInfos;
    CGFloat photoViewWH = WYMomentPhotosViewItemWidth();
    
    /// 设置显示or隐藏以及布局
    NSUInteger count = picInfos.count;
    if (count == 0) {
        [self hideAllImageViews];
    }
    NSInteger maxCols = WYMomentMaxCols(count);
    for (NSInteger i = 0; i < WYMomentPhotosMaxCount; i++) {
        
        WYMomentPhotoView *photoView = self.subviews[i];
        
        if (i < count) {
            photoView.hidden = NO;
            if (count == 1) {
                photoView.frame = self.bounds;
            }else{
                photoView.width = photoViewWH;
                photoView.height = photoViewWH;
                photoView.left = (i % maxCols) * (photoViewWH + WYMomentPhotosViewItemInnerMargin);
                photoView.top = (i / maxCols) * (photoViewWH + WYMomentPhotosViewItemInnerMargin);
            }
            photoView.picture = picInfos[i];
        }else{
            
            photoView.hidden = YES;
        }
    }
    
}

/// 隐藏所有图片
- (void)hideAllImageViews {
    for (WYMomentPhotoView *imageView in self.subviews) {
        imageView.hidden = YES;
    }
}

#pragma mark - 事件处理
- (void)tapPhoto:(UITapGestureRecognizer *)sender{
    /// 图片浏览
    NSMutableArray *items = [NSMutableArray new];
    CGFloat count = self.picInfos.count;
    for (NSUInteger i = 0; i < count; i++) {
        UIView *imgView = self.subviews[i];
        WYPicture *picture = _picInfos[i];
        WYPictureMetadata *meta = picture.largest.badgeType == WYPictureBadgeTypeGIF ? picture.largest : picture.large;
        YYPhotoGroupItem *item = [YYPhotoGroupItem new];
        item.thumbView = imgView;
        item.largeImageURL = meta.url;
        item.largeImageSize = CGSizeMake(meta.width, meta.height);
        [items addObject:item];
    }
    YYPhotoGroupView *photoBrowser = [[YYPhotoGroupView alloc] initWithGroupItems:items];
    [photoBrowser presentFromImageView:sender.view toContainer:self.window animated:YES completion:NULL];
}
@end
